// 后台脚本
console.log('Background script loaded');

// 获取所有书签文件夹的结构
async function getBookmarkFolders() {
  const allBookmarks = await chrome.bookmarks.getTree();
  const folders = [];

  function traverseBookmarks(node, path = '') {
    if (node.children) {
      // 只处理文件夹节点（没有 url 的节点）
      if (!node.url) {
        // 对于根节点使用特殊处理
        if (node.id === '0') {
          node.children.forEach(child => traverseBookmarks(child, ''));
        } else {
          const currentPath = path ? `${path}/${node.title}` : node.title;
          // 只添加非根节点的文件夹
          if (node.id !== '1' && node.id !== '2') {
            folders.push({
              id: node.id,
              title: node.title,
              path: currentPath
            });
          }
          node.children.forEach(child => traverseBookmarks(child, currentPath));
        }
      }
    }
  }

  allBookmarks.forEach(node => traverseBookmarks(node));
  return folders;
}

// 调用 Qwen API 进行智能分类
async function suggestBookmarkFolder(pageContent, folders, apiKey) {
  const prompt = `你是一个书签分类助手。请分析以下网页内容，并从现有书签文件夹中选择合适的文件夹，或建议新建文件夹。

网页内容：
${pageContent}

现有书签文件夹列表：
${folders.map(f => f.path).join('\n')}

严格按照以下JSON格式直接返回结果，不要包含任何其他内容（包括代码块标记、注释等）：
{
"useExisting": [true/false值],
"folderId": "[如果useExisting为true则填写现有文件夹ID]",
"folderPath": "[建议的文件夹完整路径]",
"reason": "[选择原因]"
}`;

  try {
    // 获取用户配置的模型类型
    const settings = await new Promise((resolve) => {
      chrome.storage.sync.get(['modelType'], resolve);
    });
    const modelType = settings.modelType || 'qwen-turbo';

    const response = await fetch('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
        'X-DashScope-SSE': 'disable'
      },
      body: JSON.stringify({
        model: modelType,
        input: {
          messages: [
            {
              role: 'system',
              content: '你是一个书签分类助手。请只返回严格的JSON格式数据，不要包含任何其他内容。'
            },
            {
              role: 'user',
              content: prompt
            }
          ]
        }
      })
    });

    const data = await response.json();
    if (!response.ok) {
      throw new Error(data.message || '调用AI服务失败');
    }

    // 清理响应文本，移除所有可能的非JSON内容
    let responseText = data.output.text;
    
    // 尝试找到JSON对象的开始和结束位置
    const startIdx = responseText.indexOf('{');
    const endIdx = responseText.lastIndexOf('}') + 1;
    
    if (startIdx === -1 || endIdx === 0) {
      throw new Error('AI返回格式错误：未找到JSON对象');
    }
    
    // 提取JSON部分
    responseText = responseText.slice(startIdx, endIdx);
    
    try {
      const suggestion = JSON.parse(responseText);
      
      // 验证返回的数据格式
      if (typeof suggestion.useExisting !== 'boolean' ||
          typeof suggestion.folderPath !== 'string' ||
          typeof suggestion.reason !== 'string' ||
          (suggestion.useExisting && typeof suggestion.folderId !== 'string')) {
        throw new Error('AI返回数据格式不符合要求');
      }
      
      return suggestion;
    } catch (parseError) {
      console.error('JSON解析失败，原始响应:', responseText);
      throw new Error('AI返回格式错误：无效的JSON格式');
    }
  } catch (error) {
    console.error('AI分类失败:', error);
    throw error;
  }
}

// 创建书签文件夹
async function createBookmarkFolder(path) {
  // 如果路径为"根目录"或为空，直接使用书签栏
  if (!path || path === '根目录') {
    return '1';
  }

  const parts = path.split('/').filter(Boolean);
  let parentId = '1';  // 默认在书签栏中创建
  
  for (const part of parts) {
    // 跳过"书签栏"和"根目录"这样的特殊文件夹名
    if (part === '书签栏' || part === '根目录' || part === '其他书签') {
      continue;
    }

    const existing = await chrome.bookmarks.search({ title: part });
    const existingInParent = existing.find(b => b.parentId === parentId);
    
    if (existingInParent) {
      parentId = existingInParent.id;
    } else {
      const newFolder = await chrome.bookmarks.create({
        parentId,
        title: part
      });
      parentId = newFolder.id;
    }
  }
  
  return parentId;
}

// 获取书签的完整路径
async function getBookmarkFullPath(bookmarkId) {
  try {
    const parts = [];
    let currentId = bookmarkId;

    while (currentId) {
      const nodes = await chrome.bookmarks.get(currentId);
      if (!nodes || nodes.length === 0) break;
      
      const node = nodes[0];
      // 检查是否到达特殊节点
      if (node.id === '0' || !node.parentId) break;
      
      // 对于"书签栏"和"其他书签"，不添加到路径中
      if (node.id === '1' || node.id === '2') {
        break;
      } else if (node.title) {
        parts.unshift(node.title);
      }
      
      currentId = node.parentId;
    }

    return parts.join('/') || '根目录';
  } catch (error) {
    console.error('获取书签路径失败:', error);
    return '根目录';  // 发生错误时返回默认值
  }
}

// 验证书签文件夹ID是否有效
async function isValidFolderId(folderId) {
  try {
    const nodes = await chrome.bookmarks.get(folderId);
    return nodes && nodes.length > 0 && !nodes[0].url; // 确保是文件夹而不是书签
  } catch {
    return false;
  }
}

// 处理来自内容脚本的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'generateSummary') {
    chrome.storage.sync.get(['apiKey', 'modelType'], async (result) => {
      if (!result.apiKey) {
        sendResponse({ error: '请先在设置中配置 API Key' });
        return;
      }

      try {
        const response = await fetch('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${result.apiKey}`,
            'X-DashScope-SSE': 'disable'
          },
          body: JSON.stringify({
            model: result.modelType || 'qwen-turbo',
            input: {
              prompt: request.prompt
            }
          })
        });

        const data = await response.json();
        if (data.output && data.output.text) {
          sendResponse({ summary: data.output.text });
        } else {
          sendResponse({ error: '生成总结失败，请稍后重试' });
        }
      } catch (error) {
        console.error('API 调用失败:', error);
        sendResponse({ error: 'API 调用失败，请检查网络连接' });
      }
    });
    return true; // 表示会异步发送响应
  }
  if (request.action === 'addBookmark') {
    // 立即开始处理
    (async () => {
      try {
        // 先检查是否存在相同URL的书签
        const results = await chrome.bookmarks.search({});
        const existingBookmark = results.find(bookmark => bookmark.url === request.url);
        
        if (existingBookmark) {
          // 找到已存在的书签，获取其完整路径
          const fullPath = await getBookmarkFullPath(existingBookmark.parentId);
          sendResponse({
            exists: true,
            bookmark: existingBookmark,
            parentTitle: fullPath
          });
          return;
        }

        // 获取API key
        const { apiKey } = await chrome.storage.sync.get(['apiKey']);
        if (!apiKey) {
          sendResponse({ error: '请先在设置中配置 API Key' });
          return;
        }

        // 获取所有书签文件夹
        const folders = await getBookmarkFolders();
        
        // 调用AI进行分类
        const suggestion = await suggestBookmarkFolder(request.pageContent, folders, apiKey);
        
        // 确定目标文件夹ID
        let targetFolderId;
        if (suggestion.useExisting) {
          // 验证AI建议的文件夹ID是否有效
          if (await isValidFolderId(suggestion.folderId)) {
            targetFolderId = suggestion.folderId;
          } else {
            // 如果ID无效，创建新文件夹
            targetFolderId = await createBookmarkFolder(suggestion.folderPath);
          }
        } else {
          targetFolderId = await createBookmarkFolder(suggestion.folderPath);
        }
        
        // 创建书签
        const bookmark = await chrome.bookmarks.create({
          parentId: targetFolderId,
          title: request.title,
          url: request.url
        });
        
        // 获取完整路径用于显示
        const fullPath = await getBookmarkFullPath(targetFolderId);
        
        sendResponse({
          success: true,
          bookmark: bookmark,
          folderPath: fullPath
        });
      } catch (error) {
        console.error('处理书签时出错:', error);
        sendResponse({ error: error.message });
      }
    })();
    
    return true; // 保持消息通道开启以支持异步响应
  }
  else if (request.action === 'openOptionsPage') {
    chrome.runtime.openOptionsPage();
    sendResponse({ success: true });
    return false;
  }
  else if (request.action === 'openToolsPage') {
    chrome.tabs.create({ url: chrome.runtime.getURL('tools.html') });
  }
  return true; // 保持消息通道开启以支持异步响应
}); 